from flask import Flask, request, send_file
import pdfkit
import os

app = Flask(__name__)

@app.route('/convert', methods=['POST'])
def convert_to_pdf():
    data = request.json
    url = data.get('url')

    if not url:
        return {"error": "URL is required"}, 400

    try:
        # 将网页转换为 PDF
        pdf_data = pdfkit.from_url(url, False)

        # 保存 PDF 文件
        pdf_path = 'output.pdf'
        with open(pdf_path, 'wb') as f:
            f.write(pdf_data)

        # 发送 PDF 文件给客户端
        return send_file(pdf_path, as_attachment=True)

    except Exception as e:
        return {"error": str(e)}, 500

if __name__ == '__main__':
    app.run(debug=True)
